package com.quanyan.place.component;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.Constants;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.wrapper.MqConsumerWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by Kingson.chan on 2016/6/17 0017.
 */
@Component("mqPayConsumer")
public class MqPayConsumer extends AbstractMqConsumer {
    private static final Logger log = LoggerFactory.getLogger(MqPayConsumer.class);
    @Value("${mq.nameServer.address}")
    private String nameServerAddress;

    @Autowired
    MqConsumerWrapper mqConsumerWrapper;

    @PostConstruct
    void run() {
        super.start();
    }

    @Override
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        //处理自身业务逻辑
        MessageExt messageExt = messages.get(0);

        //处理订单系统支付成功消息

        if(OrderPayService.TOPIC_ORDER_STATUS_NOTIFY.equals(messageExt.getTopic()) && Constants.PLACE_SYSTEM_CODE.equals(messageExt.getTags())){
            APIResponse<?> apiResponse = null;
            try {
                apiResponse = mqConsumerWrapper.orderPayOperate(messageExt);
                if(apiResponse.isRet()){
                    return MqConsumerStatus.CONSUMER_SUCCESS;
                }
            } catch (Exception e) {
                log.warn(e.getMessage());
                return MqConsumerStatus.RE_CONSUME_LATER;
            }
        }

        return MqConsumerStatus.RE_CONSUME_LATER;
    }

    @Override
    protected String getConsumerGroup() {
        return PlaceConstants.PLACE_GROUP_ORDER_PAY;
    }

    @Override
    protected String getNameServerAddress() {
         return this.nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return PlaceConstants.PLACE_INSTANCE_ORDER_PAY;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(OrderPayService.TOPIC_ORDER_STATUS_NOTIFY, Constants.PLACE_SYSTEM_CODE); //订阅订单系统支付完成的相关的topic与tag.
        return mqTopics;
    }
}
